/*
 *  Copyright:  (C) 2018 LingYun IoT System Studio
 *              All rights reserved.
 *
 *  File name:  fork_var.c
 *Description:  Usage of fork(),indicates how data is inherited.
 *
 *    Version:  1.1
 *     Author:  Guo Wenxue <guowenxue@gmail.com>
 *		        Copied by Zhu Tianyin <zhuty_cn@163.com>
 *  ChangeLog:  1.0  Release initial version in 2018.
 *              1.1  Copy and change some details on "01/09/2021".
 */
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

int  g_var = 6;  //global variate
char g_buf[] = "A string write to stdout.\n";//global string

int main(int argc, char **argv)
{
	int var = 88;
	pid_t pid;

	if(write(STDOUT_FILENO, g_buf, sizeof(g_buf)-1)<0)
	{
		printf("Write string to stdout error: %s\n", strerror(errno));
		return -1;
	}
	printf("Before fork\n");
	if((pid=fork())<0)
	{
		printf("Fork() error: %s\n", strerror(errno));
		return -2;
	}
	else if(0 == pid)
	{
		printf("Child progress PID[%d] running...\n", getpid());
		g_var++;
		var++;
	}
	else
	{
		printf("Parent process PID[%d] waiting...\n", getpid());
		sleep(1);  //Let child progress operates first.But this operation is not reliable.
	}

	printf("PID=%ld, g_var=%d, var=%d\n", (long)getpid(), g_var, var);
	return 0;
}
